** Table 11
************
clear 
cls
set more off

global MyProject "..\IBES" // Change to your folder for this project
global Output "..\Results" // change to your results path
global Datasets "...\IBES" // IBES dataset . Needs subscription via WRDS to download
global CAR "...\CAR" // path to CAR folder


*	========================	*
*	 No need to change here
*	========================	*
cap mkdir "${Output}/_temp"  
cd "${Output}/_temp"  

cap mkdir "${Output}/result" 
gl result "${Output}/result"
gl data "${MyProject}/data"



/*----------------------------------------------------*/
   /* [>   1.  create a temporary IBES dataset   <] */ 
/*----------------------------------------------------*/
use "${Datasets}/Detail History_Unadjusted.dta", clear    
rename *, lower

*     keep only fpi in (6,7)
destring fpi, replace
keep if inrange(fpi, 6, 7)														//selects quarterly forecast for the current and the next fiscal quarter! 

*     keep variables we want
keep ticker estimator analys pdf fpi value fpedats revdats revtims anndats anntims

save "ibes_temp.dta", replace


*     add IBES-CRSP link to IBES dataset
use "${Datasets}/ibes_crsp_link.dta", clear
rename *, lower
keep if score <= 1
rangejoin anndats sdate edate using "ibes_temp.dta", by(ticker)


*     Count number of estimates reported on primary/diluted basis 
bys ticker fpedats: egen p_count = total(pdf == "P") 
bys ticker fpedats: egen d_count = total(pdf == "D") 


*     Determine whether most analysts report estimates on primary/diluted basis 
gen basis = "P" if p_count > d_count
replace basis = "D" if p_count <= d_count

*     drop variables
drop p_count d_count pdf fpi


*     Keep the latest observation for a given analyst
sort ticker fpedats estimator analys anndats revdats anntims revtims
by ticker fpedats estimator analys: keep if _n == _N 							


*     save
save "ibes.dta", replace




/**********************************************************************/
/*  SECTION 2: Link Estimates with Actuals                    

/**********************************************************************/
 
--------------------------------------------------*/
   /* [>   1.  clean unadjusted actual data   <] */ 
----------------------------------------------------
use "${Datasets}/Detail History Actuals_Unadjusted.dta", clear

rename *, lower

*     keep only quarterly forecasts
tab pdicity
keep if pdicity == "QTR"

*     rename variables
rename (anndats value pends) (repdats act fpedats)

keep ticker repdats act fpedats acttims
duplicates drop
drop if missing(act)															

*     check duplicated ticker fpedats and select the last report of EPS
duplicates tag ticker fpedats, gen(dup)
bys ticker fpedats repdats (acttims): keep if dup == 0 | (dup > 0 & _n == _N)
drop dup
duplicates drop ticker fpedats, force
drop acttims

*     save
save "ibes_act.dta", replace													


 
/*----------------------------------------------------*/
   /* [>   2.  Join with the estimate piece of the data   <] */ 
/*----------------------------------------------------*/
*     Join with the estimate piece of the data
use ibes.dta, clear
merge m:1 ticker fpedats using ibes_act.dta
drop if _merge == 2
drop _merge

*     gap between announcement date and estimate report date
gen dgap = repdats - anndats												
tab dgap

keep if inrange(dgap, 0, 90)													
tab dgap

*     save
drop dgap 
keep if ~missing(repdats) & ~missing(anndats)
save "ibes1.dta", replace														//data set with merged estiamtes of multiple analysts and acctuals earnings



/*----------------------------------------------------*/
   /* [>   3.  Select all relevant combinations of Permnos and Date <] */ 
/*----------------------------------------------------*/
use ibes1.dta, clear
keep permno anndats															
duplicates drop
save ibes1_dt1.dta, replace													

use ibes1.dta, clear
keep permno repdats																
duplicates drop

rename repdats anndats
append using ibes1_dt1.dta
duplicates drop
save ibes_anndats.dta, replace 												



/*----------------------------------------------------*/
/* [>   4.  
      # Adjust all estimate and earnings announcement dates to the closest
      # preceding trading date in CRSP to ensure that adjustment factors won't
      # be missing after the merge     
<] */ 
/*----------------------------------------------------*/

*     unique non-missing-cfacshr trade dates from crsp.dsi
use "${Datasets}/stock_index_daily_crsp.dta", clear
rename *, lower

keep date
duplicates drop
save "crsp_dats.dta", replace													//CRSP trading days for which a index return is caluclted

*     unique non-missing-cfacshr trade dates from crsp.dsf
use crsp_daily, clear
rename *, lower
keep permno date cfacshr 
drop if missing(cfacshr)
/* drop cfacshr */
duplicates drop
save "unique_trading_days_cfacshr.dta", replace									//CRSP unique trading days on a stock level basis with non-missing adjustement factor


*     Create up to 10 days prior dates relative to anndats
use ibes_anndats.dta, clear
keep permno anndats
duplicates drop

forvalues i = 0 (1) 10 {
      gen anndatsL`i' = anndats - `i'
      format anndatsL`i' %td       
}  


*     reshape (transpose) the df for later join with crsp trading dates
reshape long anndatsL, i(permno anndats) j(lag)
keep  permno anndats anndatsL
rename anndatsL date															//creates 10 lags dates for each possible date on which at least an earnings or forecast announcement took place for each stock in the data! 


*     merge with crsp trading dates
*     merge the CRSP adjustment factors for all estimate and report dates
merge m:1 permno date using "unique_trading_days_cfacshr.dta"					
keep if _merge == 3																
drop _merge

*     create the dgap (days gap) variable for min selection
gen dgap = anndats - date
tab dgap

*     choosing the row with the smallest dgap for a given anndats
bys permno anndats (dgap): keep if _n == 1									
tab dgap 																		

*     save
/* keep permno anndats date */
duplicates drop
/* save tradedates.dta, replace */
save ibes_anndats.dta, replace													




/*------------------------------------ End of SECTION 2 ------------------------------------*/



/**********************************************************************/
/*  SECTION 3: Adjust Estimates with CFACSHR                    
    Notes: 

      # Put the estimate on the same per share basis as
      # company reported EPS using CRSP Adjustment factors. 
      # New_value is the estimate adjusted to be on the 
      # same basis with reported earnings.

*/
/**********************************************************************/
 
/*----------------------------------------------------*/
   /* [>   1.  create adjusted estimates   <] */ 
/*----------------------------------------------------*/
use ibes1.dta, clear

*     add cfacshr factors from CRSP
merge m:1 permno anndats using "ibes_anndats.dta", nogen keep(master match)		
drop anndats date																//drop the annoucement dates for the earnings estimates and only keep th repdate of the actual earnings!
rename cfacshr cfacshr_ann

rename repdats anndats															//anndats is now the actual annoucement date of the earnings by the company --> we have more than one observation per anndats if there is more than one estimate for that date!
merge m:1 permno anndats using "ibes_anndats.dta", nogen keep(master match)
rename (anndats cfacshr) (repdats cfacshr_rep)									


*     adjust estimate 
gen new_value = cfacshr_rep / cfacshr_ann * value								// if it is the same no change!



unique ticker fpedats estimator analys

unique ticker repdats														
unique ticker repdats basis													
unique ticker repdats basis act													
unique ticker fpedats basis repdats act											

*     save
save ibes1.dta, replace															


 
/*----------------------------------------------------*/
   /* [>   2.  Compute the median forecast based on estimates in the 90 days prior to the EAD   <] */ 
/*----------------------------------------------------*/
use ibes1.dta, clear

bys ticker fpedats basis repdats act: egen grp_permno = max(permno)
bys ticker fpedats basis repdats act: egen medest = median(new_value)
bys ticker fpedats basis repdats act: egen avgest = mean(new_value)
bys ticker fpedats basis repdats act: egen numest = count(new_value)

keep ticker fpedats basis repdats act grp_permno medest avgest numest
duplicates drop
rename grp_permno permno
save medest.dta, replace														



/**********************************************************************/
/*  SECTION 4: Merge IBES with Compustat Data                    
    Notes: 

            Required datasets:

            1) CCM link table from WRDS: "${Datasets}/CCM/data/ccm_link.dta"
            2) Compustat (comp.fundq): "fundq.dta"
     

*/


*     clean ccm link
use "${Datasets}/ccm_link.dta", clear
rename *, lower
keep if linkprim == "P" | linkprim == "C" 
keep gvkey lpermco lpermno linkdt linkenddt
rename (lpermno lpermco) (permno permco)

*     Fill linkenddt missing value (.E in SAS dataset) with a future date
count if missing(linkenddt)
replace linkenddt = mdy(12, 31, 2099) if missing(linkenddt)

save "_ccm.dta", replace


*     # high quality links from iclink
*     # score = 1 or 2
use "${Datasets}/ibes_crsp_link.dta", clear
rename *, lower
keep if score <= 2
drop score
save "iclink_hq.dta", replace


*     merge gvkey and ibes ticker
use "_ccm.dta", clear
joinby permno using "iclink_hq.dta"
drop permno permco ncusip
duplicates drop

*     find out the effective date range for the gvkey-ibes link
egen linkdt_new = rowmin(linkdt sdate)
egen linkenddt_new = rowmin(linkenddt edate)
format linkdt_new linkenddt_new %td

drop linkdt linkenddt sdate edate
bys gvkey ticker: egen linkdt = min(linkdt_new)
bys gvkey ticker: egen linkenddt = max(linkenddt_new)
format linkdt linkenddt %td
drop linkdt_new linkenddt_new
duplicates drop

save "gvkey_ticker_link.dta", replace


/*----------------------------------------------------*/
   /* [>   2.  Merge Compustat and median estimate   <] */ 
/*----------------------------------------------------*/
*     Compustat
use "${Datasets}/compustat_quarterly.dta", clear
rename *, lower

*     several filters to clean data
keep if consol == "C" & popsrc == "D" & indfmt == "INDL" & datafmt == "STD"
keep if (atq > 0 | ~missing(saleq)) & (~missing(datacqtr))

*     keep only the variables we want
keep gvkey fyearq fqtr conm datadate rdq epsfxq epspxq cshoq prccq ajexq spiq cshoq cshprq cshfdq saleq atq fyr datafqtr cshoq prccq ceqq sic

gen sic_2_digits = substr(sic,1,2), after(sic)
destring sic_2_digits, replace
label var sic_2_digits "First 2 digits for sic code from COMPUSTAT Q-File"	

destring sic, replace
ffind sic, newvar(ffind49) type(49)
mdesc ffind49  	
label var ffind49 "FF industry code (49) using non-historical SIC from COMPUSTAT Q-File"
													
gen double mcap = cshoq*prccq
gen SIZE=log(mcap)
gen double bm = ceqq/mcap
gen BM=log(ceqq/mcap)
label var mcap "Quarterly Market Cap. (cshoq*prccq)"
label var SIZE "Log of Quarterly Market Cap."
label var bm "Quarterly Book to Market (ceqq/mcap)"
label var BM "Log of Quarterly Book to Market"

winsor2 SIZE, cuts(1 99)
order SIZE_w, after(SIZE)
winsor2 BM, cuts(1 99)
order BM_w, after(BM)

*laging should be done here because we drop a lot of data in the next step
sort gvkey fyearq fqtr
by gvkey: gen SIZE_lag=SIZE[_n-1]
order SIZE_lag, after(SIZE)
by gvkey: gen BM_lag=BM[_n-1]
order BM_lag, after(BM)
label var BM_lag "One Quarter lagged Book to Market"
label var SIZE_lag "One Quarter lagged Size"

by gvkey: gen SIZE_w_lag=SIZE_w[_n-1]
order SIZE_w_lag, after(SIZE_w)
by gvkey: gen BM_w_lag=BM_w[_n-1]
order BM_w_lag, after(BM_w)
label var BM_w_lag "One Quarter lagged Book to Market"
label var SIZE_w_lag "One Quarter lagged Size"


save "comp.dta", replace


*     add IBES ticker
use "gvkey_ticker_link.dta", clear
rangejoin datadate linkdt linkenddt using "comp.dta", by(gvkey)

*     Merge with the median esitmates
gen fpedats = datadate
merge n:1 ticker fpedats using "medest.dta"

drop if _merge == 2
drop _merge

*     Sort data and drop duplicates
drop if missing(medest)															//only keep quarters in file with valid estimates and accutals
duplicates tag gvkey fqtr fyearq, gen(dup)
tab dup
   
drop dup   

duplicates drop gvkey fqtr fyearq, force
mdesc
save "sue.dta", replace															//contains repdates, i.e. actuals earnings annoucements with valid COMPUSTAT data and analyst estimates!

/*------------------------------------ End of SECTION 4 ------------------------------------*/



/**********************************************************************/
/*  SECTION 5: Calculate SUEs                    
    Notes: */
/**********************************************************************/
use sue.dta, clear

*      handling same qtr previous year
bys gvkey fqtr (fyearq): gen dif_fyearq = fyearq - fyearq[_n-1]
bys gvkey fqtr (fyearq): gen lagadj = ajexq[_n-1] if dif_fyearq == 1
bys gvkey fqtr (fyearq): gen lageps_p = epspxq[_n-1] if dif_fyearq == 1
bys gvkey fqtr (fyearq): gen lageps_d = epsfxq[_n-1] if dif_fyearq == 1
bys gvkey fqtr (fyearq): gen lagshr_p = cshprq[_n-1] if dif_fyearq == 1
bys gvkey fqtr (fyearq): gen lagshr_d = cshfdq[_n-1] if dif_fyearq == 1
bys gvkey fqtr (fyearq): gen lagspiq = spiq[_n-1] if dif_fyearq == 1


*     # handling reporting basis 
*     # Basis = P and missing are treated the same
*     actual 1
gen actual1 = epsfxq / ajexq if  basis == "D"
replace actual1 = epspxq / ajexq if basis != "D"


*     actual 2
gen temp1 = 0.65 * spiq/ cshfdq
replace temp1 = 0 if missing(temp1)

gen temp2 = 0.65*spiq/cshprq
replace temp2 = 0 if missing(temp2)

gen temp_epsfxq = epsfxq
replace temp_epsfxq = 0 if missing(temp_epsfxq)

gen temp_epspxq = epspxq
replace temp_epspxq = 0 if missing(temp_epspxq)

gen actual2 = (temp_epsfxq - temp1) / ajexq if basis == "D"
replace actual2 = (temp_epspxq - temp2) / ajexq if basis != "D"
drop temp1 temp2 temp_epspxq temp_epsfxq


*     expected1
gen expected1 = lageps_d / lagadj if basis == "D"
replace expected1 = lageps_p / lagadj if basis != "D"


*     expected2
gen temp1 = 0.65 * lagspiq / lagshr_d
replace temp1 = 0 if missing(temp1)

gen temp2 = 0.65 * lagspiq / lagshr_p
replace temp2 = 0 if missing(temp2)

gen temp_lageps_d = lageps_d
replace temp_lageps_d = 0 if missing(temp_lageps_d)

gen temp_lageps_p = lageps_p
replace temp_lageps_p = 0 if missing(temp_lageps_p)

gen expected2 = (temp_lageps_d - temp1) / lagadj if basis == "D"
replace expected2 = (temp_lageps_p - temp2) / lagadj if basis != "D"


*     # SUE calculations
gen sue1 = (actual1 - expected1) / (prccq / ajexq)
gen sue2 = (actual2 - expected2) / (prccq / ajexq)
gen sue3 = (act - medest) / prccq												//prccq = price quarter end
gen sue4 = (act - avgest) / prccq

keep ticker permno gvkey conm fyearq fqtr fyr datadate repdats rdq sue1 sue2 sue3 sue4 basis act medest numest prccq ceqq atq mcap SIZE* bm BM* SIZE*_lag BM*_lag ffind49 sic sic_2_digits
gsort gvkey -fyearq -fqtr
save "sue.dta", replace



/*----------------------------------------------------*/
   /* [>   2.  

*     Shifting the announcement date to be the next trading day
*     Defining the day after the following quarterly EA as leadrdq1   

<] */ 
/*----------------------------------------------------*/
use comp.dta, clear

*     unique rdq 
keep rdq																		
duplicates drop
drop if missing(rdq)															


*     Create up to 10 days post rdq relative to rdq
forvalues i = 0 (1) 10 {
      gen rdqF`i' = rdq + `i'
      format rdqF`i' %td       
}  

reshape long rdqF@, i(rdq) j(dgap)


*     Merge with crsp trading dates
rename rdqF date
merge m:1 date using crsp_dats.dta
keep if _merge == 3
drop _merge


*     keep only the min dgap
bys rdq (dgap): keep if _n == 1
tab dgap																	
drop dgap

*     save
rename date rdq1																
save eads1.dta, replace


*     create sue_final
use sue.dta, clear

/* replace rdq = repdats if missing(rdq) & ~missing(repdats)   // if rdq from Compustat is missing, we use repdats from IBES */

merge n:1 rdq using eads1.dta													//this ensure that the SUEs we calcualte actually can show a results in the market because there was trading in CRSP that day!
keep if _merge == 3
drop _merge

*     check dup
duplicates tag gvkey fyearq fqtr, gen(dup)
tab dup
drop dup

*     save
gsort gvkey -fyearq -fqtr
save sue_final.dta, replace



/*----------------------------------------------------*/
/* [>   3.  filter from Livnat & Mendenhall (2006)   


<] */ 
/*----------------------------------------------------*/
use sue_final.dta, clear

*     # If last gvkey then leadrdq1 = rdq1+3 months
*     # Else leadrdq1 = next rdq1
bys gvkey (fyearq fqtr): gen leadrdq1 = rdq1[_n+1]
bys gvkey (fyearq fqtr): replace leadrdq1 = rdq1 + 90 if _n == _N
bys gvkey (fyearq fqtr): replace leadrdq1 = mdy(month(leadrdq1), day(rdq1), year(leadrdq1)) if _n == _N
bys gvkey (fyearq fqtr): replace leadrdq1 = rdq1 + 90 if _n == _N & missing(leadrdq1) // 
format leadrdq1 %td


*     calculate gap between IBES EA date and Compustat EA date
gen dgap = repdats - rdq
replace dgap = 0 if missing(dgap)
drop if rdq1 == leadrdq1														


*     # Various conditioning for filtering
gen cond1 = ~missing(sue1) & ~missing(sue2) & missing(repdats)
gen cond2 = ~missing(repdats) & inrange(dgap, -1, 1)							//drops obs. where the reportings date in ibes and compustat diviate by more then 1 day 22,037 QEAs
keep if cond1 == 1 |  cond2 == 1


*     # Impose restriction on price and marketcap
keep if ~missing(rdq) & prccq >1 & mcap > 5										


*     label variables
label variable leadrdq1 "Lead Adjusted Report Date of Quarterly Earnings"
label variable basis "Primary/Diluted Basis"
label variable act "Actual Reported Earnings per Share"
label variable medest "EPS consensus forecast (median)"
label variable ticker "Historical IBES Ticker"
label variable sue1 "Earnings Surprise (Seasonal Random Walk)"
label variable sue2 "Earnings Surprise (Excluding Special items)"
label variable sue3 "Earnings Surprise (Median Analyst Forecast-based)"
label variable sue4 "Earnings Surprise (Avg. Analyst Forecast-based)"
label variable numest "Number of analyst forecasts used in Analyst-based SUE"

replace sue1= sue1*100
replace sue2= sue2*100
replace sue3= sue3*100
replace sue4= sue4*100
winsor2 sue1, cuts(1 99)
winsor2 sue2, cuts(1 99)
winsor2 sue3, cuts(1 99)
winsor2 sue4, cuts(1 99)

*     save
drop cond1 cond2
save sue_final.dta, replace														

/**********************************************************************/
 
/*----------------------------------------------------*/
   /* [>   1.  Add return data for EA date windows   <] */ 
/*----------------------------------------------------*/


use crsp_daily, clear
rename *, lower
keep permno prc date shrout ret vwretd 
gen exret=ret-vwretd
gen mcap=abs(prc*shrout)
rename vwretd mkt
drop shrout
merge m:1 date using "${Datasets}/stock_index_daily_crsp.dta", keepusing(vwretd)
keep if _merge==1 | _merge==3
drop _merge
save ds.dta, replace

use "${Datasets}/_temp/ds.dta", clear
rename *, lower
save, replace

*     # Records from sue_final that meet the condition
use sue_final.dta, clear
keep if ~missing(rdq) & ~missing(leadrdq1) & ~missing(permno) & leadrdq1 - rdq1 > 30

*     get range of Earnings Announcement window
gen lb_date = rdq1 -  5
gen ub_date = leadrdq1 + 5
format lb_date ub_date %td

*     save
keep permno rdq1  leadrdq1 sue1 sue2 sue3 sue4 lb_date ub_date
save "sfj_indexed.dta", replace

*     add return data for dates around EA date
use "sfj_indexed.dta", clear
rangejoin date lb_date ub_date using "${Datasets}/_temp/ds.dta", by(permno)

drop lb_date ub_date
save "crsprets.dta", replace


 
/*----------------------------------------------------*/
/* [>   2.  Estimate drift   

# To estimate the drift, sum daily returns over the period from  
# 1 day after the earnings announcement through the day of       
# the following quarterly earnings announcement     

<] */ 
/*----------------------------------------------------*/

use "crsprets.dta", clear

bys permno rdq1 (date): gen lagmcap = mcap[_n-1]

*     get the trading days since the announcement and keep only within 60 days after the announcement
keep if rdq1 <= date & date <= leadrdq1
bys permno rdq1 (date): gen ncount = _n - 1
tab ncount

keep if ncount <= 60

*     # Form quintiles based on SUE1-4
duplicates drop

*     SUE1
preserve
keep permno sue1 rdq1
duplicates drop
drop if missing(sue1)
egen sue1r = xtile(sue1), n(5) /* by(ncount) */
save temp.dta, replace
restore

merge m:1 permno rdq1 sue1 using temp.dta, nogen keep(master match)

*     SUE2
preserve
keep permno sue2 rdq1
duplicates drop
drop if missing(sue2)
egen sue2r = xtile(sue2), n(5) /* by(ncount) */
save temp.dta, replace
restore

merge m:1 permno rdq1 sue2 using temp.dta, nogen keep(master match)

*     SUE3
preserve
keep permno sue3 rdq1
duplicates drop
drop if missing(sue3)
egen sue3r = xtile(sue3), n(5) /* by(ncount) */
save temp.dta, replace
restore

merge m:1 permno rdq1 sue3 using temp.dta, nogen keep(master match)

*     SUE4
preserve
keep permno sue4 rdq1
duplicates drop
drop if missing(sue4)
egen sue4r = xtile(sue4), n(5) /* by(ncount) */
save temp.dta, replace
restore

merge m:1 permno rdq1 sue4 using temp.dta, nogen keep(master match)

*     save
save "peadrets.dta", replace



*calcualte CAR as market-adjusted returns in a 3 day windows
use crsp_daily.dta", clear
rename *, lower
keep permno date ret vwretd ewretd 
drop if date<=8686 | date>22645
duplicates tag permno date, gen(dup)
tab dup
drop dup
duplicates drop permno date ret, force
xtset permno date
cd "$CAR"
save crsp_daily_1983_2021, replace


*get dates of earning annoucememts reporting 
cd "${MyProject}/_temp"  
use sue_final.dta, clear 
keep permno repdats rdq1
drop if repdats<=8686 | repdats>22645
duplicates tag permno repdats, gen(dup)
tab dup
drop dup
duplicates drop permno repdats, force
xtset permno repdats
gen date=repdats
format date %td
order date permno
cd "$CAR"
save repdats, replace

*use daily merge with repdates
cd "$CAR"
use crsp_daily_1983_2021, clear
merge 1:1 permno date using repdats
tab _merge																		
keep if _merge==1 | _merge==3
gen byte eventday=_merge==3
drop _merge

*AR RAW - expected return is 0
gen event_window=eventday
sort permno date
by permno: replace event_window=1 if eventday[_n-1]==1 
by permno: replace event_window=1 if eventday[_n+1]==1
by permno: gen ret_0=ret if eventday==1 & event_window==1
by permno: gen ret_m_1=ret[_n-1] if event_window==1 & eventday==1 
by permno: gen ret_p_1=ret[_n+1] if event_window==1 & eventday==1 
egen number_of_returns= rownonmiss(ret_0 ret_m_1 ret_p_1) if eventday==1
tab number_of_returns
egen CAR= rowtotal(ret_0 ret_m_1 ret_p_1) if eventday==1 & number_of_returns==3
label var CAR "Cumulative abnormal return"

keep permno repdats CAR* 
keep if repdats!=.
mdesc 
cd "$CAR"
save CARs_1983_2021, replace

*/
cd "${MyProject}/_temp"  
use sue_final.dta, clear 
cd "$CAR"
merge m:1 permno repdats using CARs_1983_2021
keep if _merge==1 | _merge==3													
tab _merge
drop _merge

drop if repdats<=13147 | repdats>22645											
rename fyearq fyear
destring gvkey, replace

replace sue3_w = -sue3_w
g year = fyear + 1
*rename fyear year

merge m:1 permno year using bb_list
keep if year >= 2000 & year <= 2020
keep if _merge==3 | _merge==1													
drop _merge

*no negative book-value
gen byte tobedropped=ceqq<0 if ceqq!=.
tab tobedropped
tab bb if tobedropped==1		
										
drop if tobedropped==1															
drop tobedropped

mdesc bb
replace bb =0 if bb ==.

foreach var in CAR  {
replace `var' = `var'*100
}

local i = 0
												
cd "$Output"  

reg CAR bb , vce(cluster permno) 
outreg2 using event_study_ES, replace stats(coef tstat) dec(2) sortvar() drop() label excel

reg CAR bb i.year, vce(cluster permno) 
outreg2 using event_study_ES, append stats(coef tstat) dec(2) sortvar() drop() label excel

reg CAR bb i.year i.sic_2_digits, vce(cluster permno) 
outreg2 using event_study_ES, append stats(coef tstat) dec(2) sortvar() drop() label excel


reg CAR bb SIZE_w_lag BM_w_lag i.year i.sic_2_digits, vce(cluster permno) 
outreg2 using event_study_ES, append stats(coef tstat) dec(2) sortvar() drop() label excel



